<template>
  <div>
    <el-form :inline="true" :model="searchMap" style="margin:20px" ref="searchFormRef">
      <el-form-item prop="teacher_id" style="width:200px;">
        <el-select v-model="searchMap.teacher_id" placeholder="根据教师查间">
          <el-option v-for="option in teacherOptions" :key="option._id" :label="option.name" :value="option._id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="manager_id" style="width:200px;">
        <el-select v-model="searchMap.manager_id" placeholder="根据学管查间">
          <el-option v-for="option in managerOptions" :key="option._id" :label="option.name" :value="option._id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
        <el-button @click="resetForm(searchFormRef)">重置</el-button>
        <el-button type="primary" @click="handlerAdd">添加班级</el-button>
      </el-form-item>

    </el-form>
    <el-table :data="classes" style="width: 100%; height: 380px" border>
      <!--type="index" 获取索引值，从1开始； label 显示的标题; prop 数据字段名； width 列的宽度 -->
      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="classname" label="班级名称"></el-table-column>

      <el-table-column prop="teacher_id" label="授课教师" :formatter="formatTeacher"></el-table-column>

      <el-table-column prop="manager_id" label="学管" :formatter="formatManager"></el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row._id)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row._id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
    <!-- 班级添加弹窗 -->
    <el-dialog v-model="classFormVisible" title="添加班级" width="500px">
      <el-form :model="updateClass" ref="classFormRef" label-width="100px" label-position="right" style="width: 400px"
        :rules="rules">

        <el-form-item label="班级名称" prop="classname">
          <el-input v-model="updateClass.classname"></el-input>
        </el-form-item>

        <el-form-item label="授课教师" prop="teacher_id">
          <el-select v-model="updateClass.teacher_id" placeholder="请选择授课教师">
            <el-option v-for="option in teacherOptions" :label="option.name" :value="option._id"
              :key="option._id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学管" prop="manager_id">
          <el-select v-model="updateClass.manager_id" placeholder="请选择学管">
            <el-option v-for="option in managerOptions" :label="option.name" :value="option._id"
              :key="option._id"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">

          <el-button type="primary" @click="updateClass._id == null ? addData(classFormRef) : updateData(classFormRef)">
            确定
          </el-button>

          <el-button @click="classFormVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessageBox, ElMessage } from 'element-plus'
import { onMounted, ref, reactive, nextTick } from 'vue';

// 角色类、仓库
import { roleInfoData } from '@/api/role/type';
import useRoleStore from '@/store/modules/role';
const roleStore = useRoleStore()
let roleOptions = ref<roleInfoData[] | undefined>([])
// 用户类、仓库
import { userInfoData } from '@/api/user/type';
import useUserStore from '@/store/modules/user';
const userStore = useUserStore()
let userOptions = ref<userInfoData[] | undefined>([])

// 教师、学管
const teacher_role_id = ref<string | undefined>("")
const manager_role_id = ref<string | undefined>("")
const teacherOptions = ref<userInfoData[]>([])
const managerOptions = ref<userInfoData[]>([])

// 角色列表
const getRoleList = () => {
  // 仓库是否有数据
  if (roleStore.roles?.length) {
    // 读仓库获取
    roleOptions.value = roleStore.roles
    roleOptions.value?.forEach((item) => {
      if (item.name == "教师") {
        teacher_role_id.value = item._id
      } else if (item.name == "学管") {
        manager_role_id.value = item._id
      }
    })
  } else {
    // 请求获取
    roleStore.roleList().then(() => {
      roleOptions.value = roleStore.roles
      roleOptions.value?.forEach((item) => {
        if (item.name == "教师") {
          teacher_role_id.value = item._id
        } else if (item.name == "学管") {
          manager_role_id.value = item._id
        }
      })
    })
  }
}
// 用户列表
const getUserList = () => {
  if (userStore.users?.length) {
    // 读仓库获取
    userOptions.value = userStore.users
    userOptions.value?.forEach((item) => {
      if (item.role_id == teacher_role_id.value) {
        teacherOptions.value.push(item)
      } else if (item.role_id == manager_role_id.value) {
        managerOptions.value.push(item)
      }
    })
  } else {
    // 请求获取
    userStore.getUserAll().then(() => {
      userOptions.value = userStore.users
      userOptions.value?.forEach((item) => {
        if (item.role_id == teacher_role_id.value) {
          teacherOptions.value.push(item)
        } else if (item.role_id == manager_role_id.value) {
          managerOptions.value.push(item)
        }
      })
    })
  }
}

// 教师名称
const formatTeacher = (row: any, colum: any, cellValue: number, index: number) => {
  let teacher = teacherOptions?.value?.find((item) => item._id == cellValue) || {};
  return teacher.name;
}
// 学管名称
const formatManager = (row: any, colum: any, cellValue: number, index: number) => {
  let manager = managerOptions?.value?.find((item) => item._id == cellValue) || {};
  return manager.name;
}
// 重置
const searchFormRef = ref<FormInstance>()
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  getClassList()
}
// 条件查询
const searchData = () => {
  currentPage.value = 1
  getClassList()
}

onMounted(() => {
    getRoleList(),
    getUserList(),
    getClassList()
})

// 班级
import { classInfoData } from "@/api/class/type"
import useClassStore from '@/store/modules/class';
let classStore = useClassStore();
const classes = ref<classInfoData[] | undefined>([]);

let updateClass = ref<classInfoData | undefined>({
  _id: null,
  classname: "",
  teacher_id: "",
  manager_id: ""
})
let searchMap = reactive({
  teacher_id: "",
  manager_id: ""
})
// 添加弹窗
const classFormVisible = ref(false)
// 输入校验
const classFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  classname: [{ required: true, message: "请输入班级", trigger: "blur" }],
  teacher_id: [{ required: true, message: "请选择教师", trigger: "blur" }],
  manager_id: [{ required: true, message: "请选择学管", trigger: "blur" }],
})
// 添加
const handlerAdd = () => {
  classFormVisible.value = true
  nextTick(() => {
    classFormRef.value.resetFields()
  })
  updateClass.value = {
    _id: null,
    classname: "",
    teacher_id: "",
    manager_id: ""
  }
}
const addData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      classStore.addClass((updateClass.value as classInfoData)).then(
        response => {
          classFormVisible.value = false
          getClassList()
        }
      )
    } else {
      return false
    }
  })
}
// 修改
const handleEdit = (_id: string) => {
  handlerAdd()
  classStore.getClassById(_id).then(response => {
    updateClass.value = response
  }).catch()
}
const updateData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      classStore.updateClass((updateClass.value as classInfoData)).then(response => {
        classFormVisible.value = false
        getClassList()
      })
    } else { }
  })
}
// 删除
const handleDelete = (_id: string) => {
  ElMessageBox.confirm(
    "确定要删除此条数据吗？",
    "Warning",
    {
      confirmButtonText: "OK",
      cancelButtonText: "Cancel",
      type: "warning"
    }
  ).then(() => {
    classStore.deleteClass(_id).then(response => {
      getClassList()
      ElMessage({
        type: "success",
        message: "删除成功"
      })
    })
  }).catch(() => { })
}
// 班级列表
const getClassList = () => {
  classStore.getClassList({ page: currentPage.value, size: pageSize.value, searchMap })
    .then((response) => {
      classes.value = classStore.classes
      total.value = response?.total as number
      totalPage.value = total.value / pageSize.value
    })
}

// 当前页
const currentPage = ref(1)
// 单页条数
const pageSize = ref(5)
// 总条数
const total = ref(0)
// 总页数
const totalPage = ref(1)
// 单页条数变动触发
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getClassList()

}
// 当前页变动触发
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getClassList()
}
</script>

<style></style>